import {
	defineStore
} from 'pinia'
import {
	ref
} from 'vue'
import {
	getCategory,
	getCategoryGoodList
} from '../api/category.api.js'

export const useCategoryStore = defineStore(
	'category',
	() => {
		const categoryData = ref([]) // 分类
		const categoryImg = ref('') // 分类图片
		const categoryGoodListData = ref([]) // 分类商品列表数据

		// 获取分类数据
		const getCategoryData = async () => {
			let result = await getCategory()
			let newResult = result.map(item => ({
				...item,
				isActive: false
			}))
			newResult[0].isActive = true
			categoryData.value = newResult
		}
		// 选择分类
		const selectCategory = async (index, category_id) => {
			categoryImg.value = categoryData.value[index].img_url
			// 选中
			categoryData.value = categoryData.value.map(item => ({
				...item,
				isActive: item.id === category_id
			}))
			getCategoryGoodListData(category_id)
		}
		// 获取分类商品列表
		const getCategoryGoodListData = async (category_id) => {
			let result = await getCategoryGoodList(category_id)
			categoryGoodListData.value = result
		}
		
		// 跳转分类
		const goCategory = () => {
			uni.switchTab({
				url: '/pages/category/category'
			})
		}
		

		return {
			// 数据
			categoryData,
			categoryImg,
			categoryGoodListData,
			// 方法
			getCategoryData,
			selectCategory,
			getCategoryGoodListData,
			goCategory
		}
	}, {
		persist: {
			storage: {
				getItem(key) {
					return JSON.parse(uni.getStorageSync(key)); // 手动替代 destr
				},
				setItem(key, value) {
					uni.setStorageSync(key, JSON.stringify(value));
				},
			},
		}
	}
)